﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Text.RegularExpressions;

namespace converter.template
{
    public sealed class ReportColor
    {
        // Methods

        // Converts a string value to an instance of the Color structure.
        // The value could be a color name, RGB #HHHHHH, or ARGB #HHHHHHHH
        public static Color FromString(string value)
        {
            if (value.StartsWith("#")) // RGB or ARGB
                return HexToColor(value);
            else // Color name
                return Color.FromName(value);
        }

        // A value should be 7- or 9-character RGB or ARGB color string of the form
        // #HHHHHH or #HHHHHHHH.
        private static Color HexToColor(string value)
        {
            // Generate the pattern
            string pattern = @"\#";
            for (int j = 0; j < (value.Length - 1)/2; j++)
                pattern += @"([0-9|A-F|a-f]{2})";

            Match match = Regex.Match(value, pattern);

            int[] argb = new int[4];

            int i = match.Groups.Count == 4 ? 1 : 2; // starting group index
            argb[0] = i == 2 ? HexToInt(match.Groups[1].Value) : 255;

            for (int k = 1; k < 4; k++)
                argb[k] = HexToInt(match.Groups[i++].Value);

            return Color.FromArgb(argb[0], argb[1], argb[2], argb[3]);
        }

        // A value should be a string of a one byte hex-decimal representation.
        private static int HexToInt(string value)
        {
            Debug.Assert(value.Length == 2, string.Format("A hex value must be two digits in length; actual value: {0}", value));
            return Convert.ToInt32(value, 16);
        }
    }
}
